/*
 * 
 * @author		: Anand Sivadas
 * @version		: 0.1
 * @Date		: Jul 21, 2014
 * 
 */
package com.sivadas.anand.auth;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

/**
 * The Class AppBasicAuthEntryPoint.
 * @see org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint
 *
 * @author 	: Anand Sivadas
 * @Date 	: Jul 21, 2014
 */
@Component
public class AppBasicAuthEntryPoint extends BasicAuthenticationEntryPoint {

	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        final PrintWriter writer = response.getWriter();
        writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
    }

    /* (non-Javadoc)
     * @see org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("SpringDigestExample");
        super.afterPropertiesSet();
    }
}
